import { action, computed, makeObservable, observable, runInAction } from 'mobx'
import AppleItemStore from '../AppleItemStore'

class AppleBasketStore {
    apples = []
    isPicking = false
    constructor(apples) {
        if (apples) this.apples = apples
        makeObservable(this, {
            apples: observable,
            isPicking: observable,
            pickApple: action.bound,
            eatApple: action.bound,
            unEatenAppleData: computed,
            eatenAppleData: computed
        })
    }

    pickApple() {
        if (!this.isPicking) {
            this.isPicking = true
            setTimeout(() => {
                runInAction(() => {
                    this.apples.push(new AppleItemStore())
                    this.isPicking = false
                })
            }, 1000)
        }
    }

    eatApple(id) {
        const currentApple = this.apples.filter(apple => apple.id === id)[0]
        currentApple.isEaten = true
    }

    get unEatenAppleData() {
        const unEatenAppleList = this.apples.filter(apple => !apple.isEaten)
        const count = unEatenAppleList.length
        const weight = unEatenAppleList.reduce((acc, cur) => acc + cur.weight, 0)
        return {
            count,
            weight
        }
    }

    get eatenAppleData() {
        const unEatenAppleList = this.apples.filter(apple => apple.isEaten)
        const count = unEatenAppleList.length
        const weight = unEatenAppleList.reduce((acc, cur) => acc + cur.weight, 0)
        return {
            count,
            weight
        }
    }
}

export default AppleBasketStore
